package handler

import (
	"encoding/json"
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/gorilla/websocket"
	"zk/zg3_zk1/src/pro/global"

	"strconv"
)

type ChatHandler struct {
}

func NewCharHandler() *ChatHandler {
	return &ChatHandler{}
}

func (ch *ChatHandler) Chat(c *gin.Context) {
	userID, _ := strconv.Atoi(c.Query("userId"))
	//创建websocket连接  将http请求升升级成websocket连接
	conn, err := global.Upgrader.Upgrade(c.Writer, c.Request, nil)
	if err != nil {
		return
	}
	//保存用户信息
	node := global.Node{
		Conn: conn,
		Data: make(chan []byte, 50),
	}
	global.ClientMap[int64(userID)] = node
	go func() {
		for {
			_, message, err := conn.ReadMessage()
			if err != nil {
				return
			}
			var msg global.Message
			err = json.Unmarshal(message, &msg)
			if err != nil {
				var resMessage = map[string]interface{}{
					"cmd":     3,
					"content": "消息格式错误",
				}
				marshal, _ := json.Marshal(resMessage)
				node.Data <- marshal
			}
			//数据入库
			if err := global.DB.Create(&msg).Error; err != nil {
				errorMsg := map[string]interface{}{
					"cmd":     3,
					"content": "消息存储失败",
				}
				if marshal, err := json.Marshal(errorMsg); err == nil {
					node.Data <- marshal
				}
				continue
			}

			if n, ok := global.ClientMap[int64(msg.DistId)]; ok {
				n.Data <- message
			}
			fmt.Println(string(message))
		}

	}()

	go func() {
		for {
			data, ok := <-node.Data
			if ok {
				node.Conn.WriteMessage(websocket.TextMessage, data)
			}
		}
	}()
}
